<template>
  <div class="alphebet">
    <ul>
      <li
      v-for="item of letters"
      :key="item"
      :ref="item"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
      >{{item}}</li>
    </ul>
  </div>
</template>
<script>
export default {
  name: 'cityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
      // console.log(e.target.innerText)
    },
    handleTouchStart (e) {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        // 函数节流
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 102
          const index = Math.floor((touchY - this.startY) / 16)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd (e) {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
@import "~css/variable.styl"
  .alphebet
    position absolute
    top 1.57rem
    bottom 0
    width 6.4rem
    margin 0 auto
    margin-left 6rem
    ul
      display flex
      flex-direction column
      justify-content center
      position absolute
      left 0
      top 0
      bottom 0
      width .4rem
      li
        text-align center
        line-height .25rem
        color $headerBGC
        cursor pointer
</style>
